<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\DB;

class Recharge extends Model
{
    protected $table = 'recharges';

    // 不使用自增主键，使用雪花ID
    public $incrementing = false;
    protected $keyType = 'string';

    // 新状态常量
    const STATUS_PENDING        = '待处理';   // 待处理（用户刚提交）
    const STATUS_PROCESSING     = '处理中';   // 处理中（系统正在查询银行明细）
    const STATUS_MATCHED        = '已匹配';   // 已匹配（找到可能的匹配明细）
    const STATUS_CONFIRMED      = '已确认';   // 已确认（管理员确认，充值完成）
    const STATUS_FAILED         = '失败';    // 失败
    const STATUS_CANCELLED      = '已取消';   // 已取消
    const STATUS_PARTIAL_REFUND = '部分退账';  // 部分退账
    const STATUS_REFUNDED       = '已退账';   // 已退账

    protected $fillable = [
        'id',
        'tenant_id',
        'recharge_number',
        'landing_company',
        'amount',
        'bank_name',
        'bank_account',
        'status',
        'status_description',
        'remarks',
        'arrived_at',
        'settled_at',
        'refunded_at',
        'created_by',
        'updated_by'
    ];

    protected $casts = [
        'id' => 'string',
        'amount' => 'decimal:2',
        'arrived_at' => 'datetime',
        'settled_at' => 'datetime',
        'refunded_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $appends = [
        'status_display',
        'recharge_id'
    ];

    /**
     * 生成雪花ID
     */
    public static function generateSnowflakeId(): string
    {
        // 时间戳（毫秒）
        $timestamp = (int)(microtime(true) * 1000);
        
        // 机器ID（这里使用简单的随机数，生产环境应该使用配置的机器ID）
        $machineId = mt_rand(0, 1023); // 10位
        
        // 序列号（这里使用简单的随机数，生产环境应该使用递增序列）
        $sequence = mt_rand(0, 4095); // 12位
        
        // 组装雪花ID: 时间戳(42位) + 机器ID(10位) + 序列号(12位)
        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;
        
        return (string)$snowflakeId;
    }

    /**
     * 生成充值单号
     */
    public static function generateRechargeNumber(): string
    {
        return 'RECHARGE' . date('YmdHis') . mt_rand(100, 999);
    }

    /**
     * 创建时自动生成雪花ID和充值单号
     */
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = static::generateSnowflakeId();
            }
            if (empty($model->recharge_number)) {
                $model->recharge_number = static::generateRechargeNumber();
            }
        });
    }

    /**
     * 获取状态显示文本
     */
    public function getStatusDisplayAttribute(): string
    {
        $statusMap = [
            self::STATUS_PENDING => '待处理',
            self::STATUS_PROCESSING => '处理中',
            self::STATUS_MATCHED => '已匹配',
            self::STATUS_CONFIRMED => '已确认',
            self::STATUS_FAILED => '失败',
            self::STATUS_CANCELLED => '已取消',
            self::STATUS_PARTIAL_REFUND => '部分退账',
            self::STATUS_REFUNDED => '已退账',
        ];

        return $statusMap[$this->status] ?? ($this->status ?? '未知状态');
    }

    /**
     * 获取充值ID（显示用）
     */
    public function getRechargeIdAttribute(): string
    {
        return 'RCG' . substr($this->id, -8);
    }

    /**
     * 关联租户
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 租户作用域
     */
    public function scopeTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }

    /**
     * 状态作用域
     */
    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 按充值ID搜索
     */
    public function scopeSearchRechargeId($query, $rechargeId)
    {
        return $query->where('recharge_number', 'like', "%{$rechargeId}%")
                    ->orWhere('id', 'like', "%{$rechargeId}%");
    }

    /**
     * 按落地公司搜索
     */
    public function scopeSearchLandingCompany($query, $company)
    {
        return $query->where('landing_company', 'like', "%{$company}%");
    }

    /**
     * 按创建时间范围筛选
     */
    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    /**
     * 充值到账
     */
    public function markAsArrived($updatedBy, $remarks = null): bool
    {
        if ($this->status !== self::STATUS_RECHARGING) {
            return false;
        }

        $updateData = [
            'status' => self::STATUS_ARRIVED,
            'arrived_at' => now(),
            'updated_by' => $updatedBy
        ];

        if ($remarks) {
            $updateData['status_description'] = $remarks;
        }

        return $this->update($updateData);
    }

    /**
     * 充值失败
     */
    public function markAsFailed($updatedBy, $remarks): bool
    {
        if ($this->status !== self::STATUS_RECHARGING) {
            return false;
        }

        return $this->update([
            'status' => self::STATUS_RECHARGE_FAILED,
            'status_description' => $remarks,
            'updated_by' => $updatedBy
        ]);
    }

    /**
     * 标记为已结清
     */
    public function markAsSettled($updatedBy, $remarks = null): bool
    {
        if ($this->status !== self::STATUS_ARRIVED) {
            return false;
        }

        $updateData = [
            'status' => self::STATUS_SETTLED,
            'settled_at' => now(),
            'updated_by' => $updatedBy
        ];

        if ($remarks) {
            $updateData['status_description'] = $remarks;
        }

        return $this->update($updateData);
    }

    /**
     * 部分退账
     */
    public function markAsPartialRefund($updatedBy, $remarks): bool
    {
        if (!in_array($this->status, [self::STATUS_ARRIVED, self::STATUS_SETTLED])) {
            return false;
        }

        return $this->update([
            'status' => self::STATUS_PARTIAL_REFUND,
            'status_description' => $remarks,
            'updated_by' => $updatedBy
        ]);
    }

    /**
     * 全额退账
     */
    public function markAsRefunded($updatedBy, $remarks): bool
    {
        if (!in_array($this->status, [self::STATUS_ARRIVED, self::STATUS_SETTLED, self::STATUS_PARTIAL_REFUND])) {
            return false;
        }

        return $this->update([
            'status' => self::STATUS_REFUNDED,
            'refunded_at' => now(),
            'status_description' => $remarks,
            'updated_by' => $updatedBy
        ]);
    }

    /**
     * 获取所有状态选项
     */
    public static function getStatusOptions(): array
    {
        return [
            self::STATUS_PENDING => '待处理',
            self::STATUS_PROCESSING => '处理中',
            self::STATUS_MATCHED => '已匹配',
            self::STATUS_CONFIRMED => '已确认',
            self::STATUS_FAILED => '失败',
            self::STATUS_CANCELLED => '已取消',
            self::STATUS_RECHARGING => '充值中',
            self::STATUS_RECHARGE_FAILED => '充值失败',
            self::STATUS_ARRIVED => '已到账',
            self::STATUS_SETTLED => '已结清',
            self::STATUS_PARTIAL_REFUND => '部分退账',
            self::STATUS_REFUNDED => '已退账',
        ];
    }
}
